import './style.scss'
import {defineComponent, inject, onMounted, ref} from "vue";
import {ElAvatar, ElButton, ElIcon, ElInput, ElMessage, ElMessageBox, ElTable, ElTableColumn} from "element-plus";
import {CirclePlus, Search} from '@element-plus/icons-vue'
import {throttle} from "lodash";
import {sendMessage} from "@/utils/message";
import bus from "@/utils/bus";
import {useUserStore} from '@/stores/user';
import {
    addMemberApi,
    chatListApi,
    groupHistoryApi,
    historyApi,
    memberListApi,
    removeMemberApi,
    userListApi
} from "@/api/chat";
import {useRoute} from "vue-router";

export default defineComponent({
    name: "Chat",
    setup() {
        const $dialog = inject('$dialog');
        const route = useRoute();
        const baseUrl = ref(import.meta.env.VITE_APP_API_URL);
        const {userInfo} = useUserStore();

        const historyQuery = ref({});
        const chatList = ref([]);
        const chatListOrigin = ref([]);
        const chatKeyword = ref("")
        const historyUser = ref({});
        const messageList = ref([]);
        const memberList = ref([]);
        const allUserOrigin = ref([]);
        const allUser = ref([])
        const allUserKeyword = ref("")
        const text = ref('');
        const loading = ref(false)

        const getChatList = () => {
            chatListApi().then(res => {
                chatList.value = [...(res.data || [])];
                chatListOrigin.value = [...(res.data || [])];
                const uuid = route.query.group_id;
                if (uuid) {
                    if (chatList.value.map(item => item.uuid).includes(uuid)) {
                        const user = chatList.value.find(item => item.uuid === uuid)
                        user && (historyUser.value = {...user})
                    }
                    getMemberList();
                } else if (chatList.value.length) {
                    historyUser.value = {...chatList.value[0]};
                }
                handleScroll();
                getHistory();
                setTimeout(scrollToBottom, 100);
            });
        };

        const getHistory = () => {
            const api = historyUser.value.message_type === 1 ? historyApi : groupHistoryApi
            const params = historyUser.value.message_type === 1 ? {...historyUser.value} : {
                ...historyUser.value,
                type: 2
            }
            const uuid = route.query.group_id;
            if (!historyUser.value.uuid) {
                historyUser.value.uuid = uuid
            }
            loading.value = true
            api(historyUser.value.uuid, params).then(res => {
                messageList.value = [...(res.data || []), ...messageList.value];
                historyQuery.value = {
                    time: messageList.value[0] && messageList.value[0].created_at,
                };
                loading.value = false
            });
        };

        const addMember = async () => {
            const res = await userListApi()
            allUserOrigin.value = (res.data || []).filter((item) => !memberList.value.map(member => member.uuid).includes(item.uuid))
            allUser.value = [...allUserOrigin.value]
            let selection = []

            const handleSelectionChange = (val) => {
                selection = val.map(item => item.uuid)
            }

            $dialog({
                title: "添加成员",
                content: () => (
                    <>
                        <ElInput style="margin-bottom:20px" placeholder="搜索联系人" prefix-icon={Search}
                                 v-model={allUserKeyword.value}/>
                        <ElTable height="400px" data={allUser.value} onSelectionChange={handleSelectionChange}>
                            <ElTableColumn type="selection"></ElTableColumn>
                            <ElTableColumn label="头像" prop="avatar">
                                {{default: (scope) => <ElAvatar size={50} src={baseUrl.value + scope.row.avatar}/>}}
                            </ElTableColumn>
                            <ElTableColumn label="用户名" prop="username"></ElTableColumn>
                            <ElTableColumn label="昵称" prop="nickname"></ElTableColumn>
                        </ElTable>
                    </>
                ),
                showCancelButton: true,
                onConfirm: (callback) => {
                    if (!selection.length) {
                        ElMessage.error("请选择")
                        return
                    }
                    addMemberApi(route.query.group_id, {user_uuids: selection}).then(() => {
                        callback && callback()
                        ElMessage.success("添加成功")
                        getMemberList()
                    })
                }
            });
        };

        const removeMember = (item) => {
            ElMessageBox.confirm(`确定移除组员${item.nickname}吗？`, '提示').then(() => {
                removeMemberApi(route.query.group_id, {
                    user_uuids: [item.uuid]
                }).then(res => {
                    ElMessage.success("移除成功")
                    getMemberList()
                });
            })
        };

        const getMemberList = () => {
            const uuid = route.query.group_id;
            memberListApi(uuid || historyUser.value.uuid).then(res => {
                memberList.value = [...(res.data.members || [])];
                const chats = [...chatList.value]
                if (!chats.map(item => item.uuid).includes(res.data.uuid)) {
                    chats.unshift({
                        uuid: res.data.uuid,
                        details: {
                            avatar: res.data.avatar,
                            name: res.data.name,
                        },
                        message_type: 2
                    })

                    chatList.value = [...chats]

                    historyUser.value = {...chatList.value[0]};

                    handleScroll();
                    getHistory();
                    setTimeout(scrollToBottom, 100);
                }
            });
        };

        const scrollToBottom = () => {
            const el = document.querySelector('.message-content');
            if (el) {
                el.scroll({top: el.scrollHeight, behavior: 'smooth'})
            }
        };

        const handleScroll = () => {
            const el = document.querySelector('.message-content');
            if (el) {
                el.addEventListener('scroll', throttle(() => {
                    if (historyQuery.value.time && el.scrollTop === 0) getHistory();
                }, 300));
            }
        };

        const sendMsg = () => {
            if (!text.value.trim()) return;
            const data = {
                from: userInfo.uuid,
                avatar: userInfo.avatar,
                to: historyUser.value.uuid,
                content: text.value,
                contentType: 1,
                messageType: historyUser.value.message_type
            };
            messageList.value.push({
                content: data.content,
                content_type: data.contentType,
                message_type: data.messageType,
                from_user_uuid: data.from,
                time: new Date().toLocaleString(),
                details: {avatar: userInfo.avatar, name: userInfo.nickname}
            });
            sendMessage(JSON.stringify(data));
            const chats = [...chatList.value]
            const target = chats.filter((item) => item.uuid === historyUser.value.uuid)[0]
            target && (target.content = data.content)
            chatList.value = [...chats]
            text.value = '';
            setTimeout(scrollToBottom, 100);
        };

        const onMessage = () => {
            bus.on("onmessage", (data) => {
                if (data.from === "System") {
                    return
                }

                if (historyUser.value.message_type === 1 && historyUser.value.uuid !== data.from) {
                    return;
                }
                messageList.value.push({
                    content: data.content,
                    content_type: data.contentType,
                    message_type: data.messageType,
                    from_user_uuid: data.from,
                    time: new Date().toLocaleString(),
                    details: historyUser.value.details
                });
                const chats = [...chatList.value]
                const target = chats.filter((item) => item.uuid === historyUser.value.uuid)[0]
                target && (target.content = data.content)
                chatList.value = [...chats]
                scrollToBottom();
            });
        };

        const changeUser = (user) => {
            historyUser.value = {...user};
            messageList.value = [];
            historyQuery.value = {};
            memberList.value = [];
            if (user.message_type === 1) {
                getHistory();
            } else {
                getHistory()
                getMemberList()
            }
            setTimeout(scrollToBottom, 300);
        };

        onMounted(() => {
            getChatList();
            onMessage();
        });

        watch(() => chatKeyword.value, (val) => {
            if (val) {
                chatList.value = chatListOrigin.value.filter(item => item.details.name.indexOf(val) !== -1)
            } else {
                chatList.value = [...chatListOrigin.value]
            }
        })

        watch(() => allUserKeyword.value, (val) => {
            if (val) {
                allUser.value = allUserOrigin.value.filter(item => item.nickname.indexOf(val) !== -1 || item.username.indexOf(val) !== -1)
            } else {
                allUser.value = [...allUserOrigin.value]
            }
        })

        // JSX 渲染部分
        return () => (
            <div class="chat">
                {/* 左侧列表 */}
                <div class="chat-left">
                    <div class="chat-search">
                        <ElInput placeholder="搜索联系人" prefix-icon={Search} v-model={chatKeyword.value}/>
                    </div>
                    <div class="chat-list">
                        {chatList.value.map(item => (
                            <div
                                key={item.id}
                                class={["chat-item", historyUser.value.uuid === item.uuid ? "active" : ""]}
                                onClick={() => changeUser(item)}
                            >
                                <img class="avatar" src={baseUrl.value + item.details.avatar}/>
                                <div class="content">
                                    <div class="info">
                                        <div class="name">{item.details.name}</div>
                                    </div>
                                    <div class="message">{item.content}</div>
                                </div>
                            </div>
                        ))}
                    </div>
                </div>

                {/* 右侧成员列表 */}
                {historyUser.value.message_type === 2 && (
                    <div className="chat-right">
                        <div className="member-list">
                            {memberList.value.map(item => (
                                <div className="member-item" key={item.uuid}>
                                    <img src={baseUrl.value + item.avatar}/>
                                    <div>{item.nickname}</div>
                                    <ElIcon class="remove" size="20" color="red"
                                            onClick={() => removeMember(item)}><CircleClose/></ElIcon>
                                </div>
                            ))}
                            <div className="add-member" onClick={addMember}>
                                <ElIcon size="40"><CirclePlus/></ElIcon>
                            </div>
                        </div>
                    </div>
                )}

                {/* 中间聊天区 */}
                <div class="chat-center" style={{marginRight: historyUser.value.message_type === 2 ? '320px' : '20px'}}>
                    <div class="profile">
                        <div class="info">
                            <div class="name">{historyUser.value?.details?.name}</div>
                        </div>
                    </div>

                    <div class="message-content" v-loading={loading.value}>
                        {messageList.value.map((item, index) => (
                            <div
                                key={index}
                                class={["message-item", item.from_user_uuid === userInfo.uuid ? "isOwner" : ""]}
                            >
                                <img class="avatar" src={baseUrl.value + item.details.avatar}/>
                                <div class="msg">
                                    <div class="desc">{item.content}</div>
                                    {/*<div class="time">{item.time}</div>*/}
                                </div>
                            </div>
                        ))}
                    </div>

                    <div class="send-bottom">
                        <ElInput placeholder="输入消息" v-model={text.value}>
                            {{
                                append: () => <ElButton type="primary" onClick={sendMsg}>发送</ElButton>
                            }}
                        </ElInput>
                    </div>
                </div>
            </div>
        );
    }
});
